// 消息通知UI
export class UIManager {
    constructor() {
        this.loadingOverlay = null;
        this.notifications = [];
        this.init();
    }

    init() {
        // 确保loadingOverlay元素存在
        if (!document.getElementById('loadingOverlay')) {
            const overlay = document.createElement('div');
            overlay.id = 'loadingOverlay';
            overlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.7);
                display: none;
                align-items: center;
                justify-content: center;
                z-index: 1000;
            `;
            
            const spinner = document.createElement('div');
            spinner.className = 'loading-spinner';
            spinner.style.cssText = `
                background: white;
                padding: 32px;
                border-radius: 12px;
                text-align: center;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            `;
            
            const icon = document.createElement('i');
            icon.className = 'fas fa-spinner fa-spin';
            icon.style.cssText = `
                font-size: 32px;
                color: #3498db;
                margin-bottom: 16px;
                display: block;
            `;
            
            const message = document.createElement('p');
            message.style.cssText = `
                color: #495057;
                font-weight: 500;
                margin: 0;
            `;
            message.textContent = '正在加载...';
            
            spinner.appendChild(icon);
            spinner.appendChild(message);
            overlay.appendChild(spinner);
            document.body.appendChild(overlay);
        }
        
        this.loadingOverlay = document.getElementById('loadingOverlay');
        this.setupNotificationSystem();
    }

    setupNotificationSystem() {
        // 创建通知容器
        if (!document.getElementById('notificationContainer')) {
            const container = document.createElement('div');
            container.id = 'notificationContainer';
            container.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 2000;
                max-width: 400px;
            `;
            document.body.appendChild(container);
        }
    }

    showLoading(show = true, message = '正在加载...') {
        if (!this.loadingOverlay) return;

        if (show) {
            this.loadingOverlay.style.display = 'flex';
            const messageElement = this.loadingOverlay.querySelector('p');
            if (messageElement) {
                messageElement.textContent = message;
            }
        } else {
            this.loadingOverlay.style.display = 'none';
        }
    }

    showNotification(message, type = 'info', duration = 5000) {
        const notification = this.createNotification(message, type);
        const container = document.getElementById('notificationContainer');
        
        if (container) {
            container.appendChild(notification);
            
            // 添加进入动画
            setTimeout(() => {
                notification.style.transform = 'translateX(0)';
                notification.style.opacity = '1';
            }, 10);
            
            // 自动移除
            if (duration > 0) {
                setTimeout(() => {
                    this.removeNotification(notification);
                }, duration);
            }
        }
        
        return notification;
    }

    createNotification(message, type) {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.style.cssText = `
            background: white;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            transform: translateX(100%);
            opacity: 0;
            transition: all 0.3s ease;
            border-left: 4px solid ${this.getTypeColor(type)};
            display: flex;
            align-items: center;
            justify-content: space-between;
            max-width: 100%;
            word-wrap: break-word;
        `;

        const content = document.createElement('div');
        content.style.cssText = `
            display: flex;
            align-items: center;
            flex: 1;
        `;

        const icon = document.createElement('i');
        icon.className = `fas ${this.getTypeIcon(type)}`;
        icon.style.cssText = `
            color: ${this.getTypeColor(type)};
            margin-right: 8px;
            font-size: 17.6px;
        `;

        const text = document.createElement('span');
        text.textContent = message;
        text.style.cssText = `
            color: #333;
            font-size: 14.4px;
        `;

        const closeButton = document.createElement('button');
        closeButton.innerHTML = '<i class="fas fa-times"></i>';
        closeButton.style.cssText = `
            background: none;
            border: none;
            color: #999;
            cursor: pointer;
            padding: 4px;
            margin-left: 8px;
            border-radius: 4px;
            transition: background-color 0.2s;
        `;

        closeButton.addEventListener('click', () => {
            this.removeNotification(notification);
        });

        closeButton.addEventListener('mouseenter', () => {
            closeButton.style.backgroundColor = '#f0f0f0';
        });

        closeButton.addEventListener('mouseleave', () => {
            closeButton.style.backgroundColor = 'transparent';
        });

        content.appendChild(icon);
        content.appendChild(text);
        notification.appendChild(content);
        notification.appendChild(closeButton);

        return notification;
    }

    removeNotification(notification) {
        notification.style.transform = 'translateX(100%)';
        notification.style.opacity = '0';
        
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }

    getTypeColor(type) {
        const colors = {
            success: '#28a745',
            error: '#dc3545',
            warning: '#ffc107',
            info: '#17a2b8'
        };
        return colors[type] || colors.info;
    }

    getTypeIcon(type) {
        const icons = {
            success: 'fa-check-circle',
            error: 'fa-exclamation-circle',
            warning: 'fa-exclamation-triangle',
            info: 'fa-info-circle'
        };
        return icons[type] || icons.info;
    }

    showSuccess(message, duration = 3000) {
        return this.showNotification(message, 'success', duration);
    }

    showError(message, duration = 5000) {
        return this.showNotification(message, 'error', duration);
    }

    showWarning(message, duration = 4000) {
        return this.showNotification(message, 'warning', duration);
    }

    showInfo(message, duration = 3000) {
        return this.showNotification(message, 'info', duration);
    }

    // 确认对话框
    showConfirmDialog(message, title = '确认', onConfirm = null, onCancel = null) {
        return new Promise((resolve) => {
            const overlay = document.createElement('div');
            overlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 3000;
            `;

            const dialog = document.createElement('div');
            dialog.style.cssText = `
                background: white;
                border-radius: 12px;
                padding: 32px;
                max-width: 400px;
                width: 90%;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
                text-align: center;
            `;

            const titleElement = document.createElement('h3');
            titleElement.textContent = title;
            titleElement.style.cssText = `
                margin-bottom: 16px;
                color: #2c3e50;
                font-size: 19.2px;
            `;

            const messageElement = document.createElement('p');
            messageElement.textContent = message;
            messageElement.style.cssText = `
                margin-bottom: 32px;
                color: #495057;
                line-height: 1.5;
            `;

            const buttonContainer = document.createElement('div');
            buttonContainer.style.cssText = `
                display: flex;
                gap: 16px;
                justify-content: center;
            `;

            const cancelButton = document.createElement('button');
            cancelButton.textContent = '取消';
            cancelButton.style.cssText = `
                padding: 12px 24px;
                border: 1px solid #dee2e6;
                border-radius: 6px;
                background: white;
                color: #6c757d;
                cursor: pointer;
                transition: all 0.3s ease;
            `;

            const confirmButton = document.createElement('button');
            confirmButton.textContent = '确认';
            confirmButton.style.cssText = `
                padding: 12px 24px;
                border: none;
                border-radius: 6px;
                background: #3498db;
                color: white;
                cursor: pointer;
                transition: all 0.3s ease;
            `;

            const closeDialog = (result) => {
                document.body.removeChild(overlay);
                resolve(result);
                
                if (result && onConfirm) {
                    onConfirm();
                } else if (!result && onCancel) {
                    onCancel();
                }
            };

            cancelButton.addEventListener('click', () => closeDialog(false));
            confirmButton.addEventListener('click', () => closeDialog(true));

            // 添加悬停效果
            cancelButton.addEventListener('mouseenter', () => {
                cancelButton.style.backgroundColor = '#f8f9fa';
            });
            cancelButton.addEventListener('mouseleave', () => {
                cancelButton.style.backgroundColor = 'white';
            });

            confirmButton.addEventListener('mouseenter', () => {
                confirmButton.style.backgroundColor = '#2980b9';
            });
            confirmButton.addEventListener('mouseleave', () => {
                confirmButton.style.backgroundColor = '#3498db';
            });

            // ESC键关闭
            const handleKeyDown = (event) => {
                if (event.key === 'Escape') {
                    closeDialog(false);
                    document.removeEventListener('keydown', handleKeyDown);
                }
            };
            document.addEventListener('keydown', handleKeyDown);

            buttonContainer.appendChild(cancelButton);
            buttonContainer.appendChild(confirmButton);
            dialog.appendChild(titleElement);
            dialog.appendChild(messageElement);
            dialog.appendChild(buttonContainer);
            overlay.appendChild(dialog);
            document.body.appendChild(overlay);

            // 聚焦确认按钮
            setTimeout(() => confirmButton.focus(), 100);
        });
    }

    // 进度条
    showProgressBar(title = '处理中...') {
        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 3000;
        `;

        const container = document.createElement('div');
        container.style.cssText = `
            background: white;
            border-radius: 12px;
            padding: 32px;
            min-width: 300px;
            text-align: center;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        `;

        const titleElement = document.createElement('h3');
        titleElement.textContent = title;
        titleElement.style.cssText = `
            margin-bottom: 16px;
            color: #2c3e50;
        `;

        const progressContainer = document.createElement('div');
        progressContainer.style.cssText = `
            width: 100%;
            height: 8px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 16px;
        `;

        const progressBar = document.createElement('div');
        progressBar.style.cssText = `
            height: 100%;
            background: linear-gradient(90deg, #3498db, #2980b9);
            width: 0%;
            transition: width 0.3s ease;
        `;

        const percentageText = document.createElement('div');
        percentageText.textContent = '0%';
        percentageText.style.cssText = `
            color: #6c757d;
            font-size: 14.4px;
        `;

        progressContainer.appendChild(progressBar);
        container.appendChild(titleElement);
        container.appendChild(progressContainer);
        container.appendChild(percentageText);
        overlay.appendChild(container);
        document.body.appendChild(overlay);

        return {
            updateProgress: (percentage) => {
                progressBar.style.width = `${Math.min(100, Math.max(0, percentage))}%`;
                percentageText.textContent = `${Math.round(percentage)}%`;
            },
            updateTitle: (newTitle) => {
                titleElement.textContent = newTitle;
            },
            close: () => {
                if (overlay.parentNode) {
                    document.body.removeChild(overlay);
                }
            }
        };
    }

    // 工具提示
    showTooltip(element, text, position = 'top') {
        const tooltip = document.createElement('div');
        tooltip.textContent = text;
        tooltip.style.cssText = `
            position: absolute;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 8px;
            border-radius: 4px;
            font-size: 12.8px;
            white-space: nowrap;
            z-index: 4000;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;

        document.body.appendChild(tooltip);

        const updatePosition = () => {
            const rect = element.getBoundingClientRect();
            const tooltipRect = tooltip.getBoundingClientRect();

            let left, top;

            switch (position) {
                case 'top':
                    left = rect.left + (rect.width - tooltipRect.width) / 2;
                    top = rect.top - tooltipRect.height - 8;
                    break;
                case 'bottom':
                    left = rect.left + (rect.width - tooltipRect.width) / 2;
                    top = rect.bottom + 8;
                    break;
                case 'left':
                    left = rect.left - tooltipRect.width - 8;
                    top = rect.top + (rect.height - tooltipRect.height) / 2;
                    break;
                case 'right':
                    left = rect.right + 8;
                    top = rect.top + (rect.height - tooltipRect.height) / 2;
                    break;
            }

            tooltip.style.left = `${left}px`;
            tooltip.style.top = `${top}px`;
        };

        updatePosition();
        setTimeout(() => {
            tooltip.style.opacity = '1';
        }, 10);

        const hideTooltip = () => {
            tooltip.style.opacity = '0';
            setTimeout(() => {
                if (tooltip.parentNode) {
                    document.body.removeChild(tooltip);
                }
            }, 300);
        };

        return { hide: hideTooltip };
    }

    // 更新UI状态
    updateSeriesCount(count) {
        const element = document.getElementById('seriesCount');
        if (element) {
            element.textContent = count;
        }
    }

    updateImageInfo(info) {
        const element = document.getElementById('imageInfo');
        if (element) {
            element.textContent = info;
        }
    }

    updateCurrentImageIndex(current, total) {
        const currentElement = document.getElementById('currentImageIndex');
        const totalElement = document.getElementById('totalImages');
        
        if (currentElement) {
            currentElement.textContent = current;
        }
        if (totalElement) {
            totalElement.textContent = total;
        }
    }

    // 禁用/启用按钮
    setButtonEnabled(buttonId, enabled) {
        const button = document.getElementById(buttonId);
        if (button) {
            button.disabled = !enabled;
        }
    }

    // 设置按钮加载状态
    setButtonLoading(buttonId, loading, originalText = null) {
        const button = document.getElementById(buttonId);
        if (!button) return;

        if (loading) {
            button.disabled = true;
            button.dataset.originalText = button.textContent;
            button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        } else {
            button.disabled = false;
            button.textContent = originalText || button.dataset.originalText || button.textContent;
        }
    }

    // 清空容器
    clearContainer(containerId) {
        const container = document.getElementById(containerId);
        if (container) {
            container.innerHTML = '';
        }
    }

    // 显示/隐藏元素
    showElement(elementId, show = true) {
        const element = document.getElementById(elementId);
        if (element) {
            element.style.display = show ? 'block' : 'none';
        }
    }

    // 添加CSS类
    addClass(elementId, className) {
        const element = document.getElementById(elementId);
        if (element) {
            element.classList.add(className);
        }
    }

    // 移除CSS类
    removeClass(elementId, className) {
        const element = document.getElementById(elementId);
        if (element) {
            element.classList.remove(className);
        }
    }

    // 切换CSS类
    toggleClass(elementId, className) {
        const element = document.getElementById(elementId);
        if (element) {
            element.classList.toggle(className);
        }
    }
} 